package ch.ffhs.radarpp.managers;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

import ch.ffhs.radarpp.model.LoginInformation;
import ch.ffhs.radarpp.model.Settings;

import android.content.Context;
/**
 * 
 * @author Beda
 *
 */
public class PersistentDataManager {

	private static LoginInformation loginInformation;	
	private static Settings settings;


	public static void setLoginInfo(Context context, LoginInformation loginInformation) {
		PersistentDataManager.loginInformation = loginInformation;

		writeObject(context, loginInformation, "logininfo.dat");
	}

	public static LoginInformation getLoginInfo(Context context) {
		if (loginInformation == null) {
			loginInformation = (LoginInformation) readObject(context, "logininfo.dat");
		}
		return loginInformation;

	}

	public static Settings getAppSettings(Context context) {
		if (settings == null) {
			try {
				settings = (Settings) readObject(context, "settings.dat");
			} catch (Exception ex) {
				settings = null;
				ex.printStackTrace();
			}

			if (settings == null) {
				settings = new Settings(false, 20);
			}

			if (settings.getGPSTimeInterval() == 0) {
				settings.setGPSTimeInterval(20);
			}
		}
		return settings;
	}

	public static void setAppSettings(Context context, Settings settings) {
		PersistentDataManager.settings = settings;

		writeObject(context, settings, "settings.dat");
	}

	private static Object readObject(Context context, String file) {
		FileInputStream fis;
		Object result = null;
		try {

			fis = context.openFileInput(file);
			ObjectInputStream is = new ObjectInputStream(fis);
			result = is.readObject();
			is.close();

		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
		return result;
	}

	private static void writeObject(Context context, Object object, String file) {
		FileOutputStream fos;

		try {
			fos = context.openFileOutput(file, Context.MODE_PRIVATE);

			ObjectOutputStream os = new ObjectOutputStream(fos);
			os.writeObject(object);
			os.close();

		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	
	

}
